package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Api("地址相关接口")
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;


    /*
     * 新增地址
     */
    @PostMapping
    @ApiOperation("新增地址")
    public Result add(@RequestBody AddressBook addressBook) {
        log.info("新增地址: {}", addressBook);
        addressBookService.addAddressBook(addressBook);
        return Result.success();
    }

    /*
     * 查询当前登录用户的所有地址信息
     */
    @GetMapping("/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> list(){
        log.info("查询当前登录用户的所有地址信息: ");
        List<AddressBook> list = addressBookService.showAddressBook();
        if (!list.isEmpty()) {
            return Result.success(list);
        }
        return Result.error("当前用户还没有地址信息");

    }

    /*
     * 查询默认地址
     */
    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> defaultAddressBook(){
        log.info("查询默认地址: ");
        AddressBook addressBook = addressBookService.showDefaultAddressBook();
        if(addressBook != null){
            return Result.success(addressBook);
        }
        return Result.error("没有查询到默认地址");
    }

    /*
     * 根据id查询地址
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> getById(@PathVariable Long id){
        log.info("根据id查询地址: {} ",id);
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    /*
     * 根据id修改地址
     */
    @PutMapping
    @ApiOperation("根据id修改地址")
    public Result update(@RequestBody AddressBook addressBook){
        log.info("根据id修改地址 : {} ",addressBook.getId());
        addressBookService.update(addressBook);
        return Result.success();
    }

    /*
     * 设置默认地址
     */
    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result updateDefault(@RequestBody AddressBook addressBook){
        log.info("设置默认地址 : {} ",addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.updateDefault(addressBook);
        return Result.success();
    }

    /*
     * 根据id删除地址
     */
    @DeleteMapping()
    @ApiOperation("根据id删除地址")
    public Result delete(Long id){
        log.info("根据id删除地址: {}",id);
        addressBookService.deleteById(id);
        return Result.success();
    }

}
